package Atop100.huawei;

import java.io.*;
import java.util.Deque;
import java.util.LinkedList;
import java.util.StringTokenizer;

public class Main {

    private static  class FastScanner {
        BufferedReader br;
        StringTokenizer st;
        public FastScanner(InputStream stream){
            br =  new BufferedReader(new InputStreamReader(stream), 32768);
            st = null;
        }
        String next() {
            while (st == null ||  !st.hasMoreTokens())
                try {
                    st=new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }
    }


    public static void main(String[] args) {
        new Main().solve();
    }
    int m,n;
    int[][] grid;
    void solve() {
        PrintWriter pwin = new PrintWriter(new OutputStreamWriter(System.out));
        FastScanner fsc = new FastScanner(System.in);
        m = fsc.nextInt();;
        n = fsc.nextInt();
        grid = new int[m][n];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                grid[i][j] = fsc.nextInt();
            }
        }
        int[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}};
        int res = 10000001;
        for (int i = 0; i < m; i++) {
            if (grid[i][0] == 1) {
                Deque<int[]> dq = new LinkedList<>();
                dq.add(new int[]{0,i,0});
                boolean[][] used = new boolean[m][n];
                used[i][0] = true;
                while (!dq.isEmpty()) {
                    int[] a = dq.poll();
                    int d = a[0], x = a[1], y = a[2];
                    if (y == n-1) {
                        res = Math.min(res, d);
                    }
                    for (int[] dir : dirs) {
                        int nx = x + dir[0],  ny = y + dir[1];
                        if (nx < 0 || ny < 0 || nx >= m || ny >= n || used[nx][ny] || grid[nx][ny] != 1) continue;
                        used[nx][ny] = true;
                        dq.add(new int[]{d+1, nx,ny});
                    }
                }
            }
        }
        if (res != 10000001) pwin.println(res);
        else pwin.println(-1);
        pwin.flush();
    }
}